package com.echo.register.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.register.client.hosp.HospitalFeignClient;
import com.echo.register.common.exception.RegisterException;
import com.echo.register.common.helper.HttpRequestHelper;
import com.echo.register.common.result.ResultCodeEnum;
import com.echo.register.enums.OrderStatusEnum;
import com.echo.register.enums.PaymentStatusEnum;
import com.echo.register.model.order.OrderInfo;
import com.echo.register.model.order.PaymentInfo;
import com.echo.register.order.mapper.PaymentInfoMapper;
import com.echo.register.order.service.OrderService;
import com.echo.register.order.service.PaymentService;
import com.echo.register.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: PaymentServiceImpl
 * @Package: com.echo.register.order.service.impl
 * @Description:
 * @Author 谢同学
 * @Create 2024/1/8 16:23
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PaymentServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    /**
     * 保存交易记录
     *
     * @param orderInfo   订单详情
     * @param paymentType 支付类型（支付宝 微信)
     */
    @Override
    public void savePsavePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        // 先查看是否已经存在订单
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderId, orderInfo.getId())
                .eq(PaymentInfo::getPaymentType, paymentType));
        if (count > 0) {
            return;
        }
        PaymentInfo paymentInfo = new PaymentInfo();
        // 设置订单记录
        paymentInfo.setOrderId(orderInfo.getId()); // 订单id
        paymentInfo.setPaymentType(paymentType); // 支付方式
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo()); // 对外业务编号(订单交易号)
        paymentInfo.setTotalAmount(orderInfo.getAmount()); // 订单金额
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus()); // 支付状态
        // 交易内容
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + "|" + orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        // 插入数据
        baseMapper.insert(paymentInfo);
    }

    /**
     * 支付成功处理逻辑（更新支付记录&订单状态&对接医院系统更新订单）
     *
     * @param outTradeNo  订单id
     * @param paymentType 支付类型
     * @param paramMap    微信响应数据
     */
    @Override
    public void paySuccess(String outTradeNo, Integer paymentType, Map<String, String> paramMap) {
        // 更新支付记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, outTradeNo)
                .eq(PaymentInfo::getPaymentType, paymentType));
        if (paymentInfo == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        paymentInfo.setTradeNo(paramMap.get("transaction_id"));// 微信支付订单号
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus()); // 支付状态 2：已支付
        paymentInfo.setCallbackTime(new Date()); // 回调时间
        paymentInfo.setCallbackContent(JSONObject.toJSONString(paramMap));//回调信息
        baseMapper.updateById(paymentInfo);


        // 更新订单状态
        OrderInfo orderInfo = orderService.getOrderInfo(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus()); // 订单状态  1：已支付
        orderService.updateById(orderInfo);


        // 对接医院系统更新订单
        // 获取签名信息
        SignInfoVo singKeyOrder = hospitalFeignClient.getSingKeyOrder(orderInfo.getHoscode());
        if (singKeyOrder == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        // 封装请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("hoscode", orderInfo.getHoscode());//给医院分配的唯一标识
        map.put("hosRecordId", orderInfo.getHosRecordId());//预约记录唯一标识
        map.put("timestamp", HttpRequestHelper.getTimestamp());//时间戳
        map.put("sign", HttpRequestHelper.getSign(map, singKeyOrder.getSignKey()));//验签参数。

        JSONObject jsonObject = HttpRequestHelper.sendRequest(map, singKeyOrder.getApiUrl() + "/order/updatePayStatus");
        if (jsonObject.getInteger("code") != 200) {
            throw new RegisterException(jsonObject.getString("message"),jsonObject.getInteger("code"));
        }
    }

    /**
     * 查询支付记录
     *
     * @param orderId     订单id
     * @param paymentType 交易类型
     * @return 支付记录
     */
    @Override
    public PaymentInfo getPaymentInfo(Long orderId, Integer paymentType) {
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderId, orderId).eq(PaymentInfo::getPaymentType, paymentType));
        if (paymentInfo == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        return paymentInfo;
    }
}
